package com.wx_shop.api.util;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpClientUtils {
	
	private static final Logger LOG = LoggerFactory.getLogger(HttpClientUtils.class);
	
	private static PoolingHttpClientConnectionManager connectionManager;
	static {
		connectionManager = new PoolingHttpClientConnectionManager();
		connectionManager.setMaxTotal(500);
		connectionManager.setDefaultMaxPerRoute(50);// 例如默认每路由最高50并发，具体依据业务来定
	}

	private static CloseableHttpClient getHttpClient() {
		CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager)
		// .setKeepAliveStrategy(kaStrategy)
				.setDefaultRequestConfig(RequestConfig.custom().build()).build();
		return httpClient;
	}

	public static String postUrlWithParams(String url, Map<String, String> params, Map<String, String> heads) {
		CloseableHttpClient mHttpClient = getHttpClient();
		
		
		// 装填参数
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		if (params != null) {
			for (Entry<String, String> entry : params.entrySet()) {
				nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
			}
		}
		
		// 设置参数到请求对象中
		HttpPost httpPost = new HttpPost(url);
		
		RequestConfig requestConfig = RequestConfig.custom()    
		        .setConnectTimeout(5000).setConnectionRequestTimeout(1000)    
		        .setSocketTimeout(5000).build();    
		httpPost.setConfig(requestConfig);    
		
		CloseableHttpResponse response = null;
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
			httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
			httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

			String body = "";
			// 执行请求操作，并拿到结果（同步阻塞）
			response = mHttpClient.execute(httpPost);
			// 获取结果实体
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				// 按指定编码转换结果实体为String类型
				body = EntityUtils.toString(entity, "utf-8");
			}
			EntityUtils.consume(entity);
			// 释放链接
			
			LOG.info("saveDevice post body={}", body);
			
			return body;
		} catch (Exception e) {
			e.printStackTrace();
			LOG.error("saveDevice post body={}", e.getMessage(), e);
		} finally  {
			try {
				if(response != null ) {
					response.close();
				}
			} catch (IOException e) {
				LOG.error("saveDevice post IOException={}", e.getMessage(), e);
			}
		}
		return null;
	}
	
	// 添加默认header
	public static void addCommHeader(HttpRequestBase request) {
		Map<String, String> header = new HashMap<String, String>() {
			private static final long serialVersionUID = 1L;

			{
				put("accept", "*/*");
				put("connection", "Keep-Alive");
				put("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			}
		};

		for (Iterator<String> it = header.keySet().iterator(); it.hasNext();) {
			String key = it.next();
			request.setHeader(key, header.get(key));
		}
	}

}
